import axios from "axios";

// 创建新的axios实例
const service: any = axios.create();
const message = window["$message"];

// 请求拦截
service.interceptors.request.use(
  // 请求成功
  (req: any) => {
    // 下载文件
    if (req.isDownLoadFile) {
      req.responseType = "blob";
    }
    // 上传文件
    if (req.isUploadFile && req.headers) {
      req.headers["Content-Type"] = "multipart/form-data";
    }
    if (req.isParams) {
      req.params = req.data;
      req.data = {};
    }
    return req;
  },

  //请求失败
  (err: any) => {
    return Promise.reject(err);
  }
);

// 响应拦截
service.interceptors.response.use(
  // 响应成功
  (res: any) => {
    // res.config就是发起请求时的配置信息
    // 如果是下载文件直接返回
    if (res.config.isDownLoadFile) {
      return res;
    }
    const { code } = res.data;
    const successCode = "0,200";
    if (successCode.includes(code)) {
      return res.data;
    } else {
      if (res.config.isAlertErrorMsg) {
        message && message.error(res.data.errorMsg || "未知的错误");
      }
      return Promise.reject(res.data);
    }
  },

  // 响应失败
  (err: any) => {
    return Promise.reject(err);
  }
);

export function request({
  url,
  method,
  data,
  isParams,
  isUploadFile,
  isDownLoadFile,
  baseURL,
  timeout,
  isAlertErrorMsg,
}: any): any {
  return service({
    url: url,
    method: method ?? "GET",
    data: data ?? {},
    isParams: isParams ?? false,
    isUploadFile: isUploadFile ?? false,
    isDownLoadFile: isDownLoadFile ?? false,
    baseURL: baseURL ?? import.meta.env.VITE_BASE_URL,
    timeout: timeout ?? 15000,
    isAlertErrorMsg: isAlertErrorMsg ?? true,
  });
}

export default request;
